package com.geek.shiro;

import com.geek.model.MarketUser;
import com.geek.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 自定的Realm要继承AuthorizingRealm
 * doGetAuthenticationInfo：获得认证信息  → credentials
 * doGetAuthorizationInfo：获得授权信息  → permissions
 */
@Component
public class CustomRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;

    /**
     * 该方法获得认证信息
     *
     * @param authenticationToken → subject.login传入的参数 new UsernamePasswordToken(username, password)
     *                            credentials → 系统内的密码(凭据)
     *                            主要方式：根据用户名(UsernamePasswordToken中的username)来做查询
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        // subject.login中的UsernamePasswordToken中的username
        String username = token.getUsername();
        // 查询系统中的用户信息(→ password)
        MarketUser marketUser = userService.findByName(username);
        String credentials = marketUser.getPassword();
        /**
         * 参数1：放入的就是当前用户的信息(Principal)，可以通过subject来获取
         */
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(marketUser.getId(),
                credentials, getName());
        return authenticationInfo;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }


}
